package com.bgs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bgs.common.MD5;
import com.bgs.common.R;
import com.bgs.pojo.User;
import com.bgs.service.TokenService;
import com.bgs.service.UserService;
import com.bgs.utils.NormalConstant;
import com.bgs.utils.TokenHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: D.c_h
 * @create: 2021-07-08 22:11
 **/
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenHelper tokenHelper;

    @Autowired
    private UserService userService;

    @Override
    public R login(Map<String, String> info) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        String pass = MD5.encrypt(info.get("password"));
        wrapper.eq("id_card", info.get("username"));
        wrapper.eq("password", pass);
        User user = userService.getOne(wrapper);
        if (null != user && user.getPassword().equals(pass)) {
            String s = tokenHelper.create(user.getUserId());
            if (!StringUtils.isEmpty(s)) {
                return R.ok().data("token", s);
            } else {
                return R.error();
            }
        } else {
            return R.error().message(NormalConstant.CARD_OR_PASSWORD_ERROR);
        }
    }

    @Override
    public R logout(HttpServletRequest request) {
        boolean b = tokenHelper.delete(request);
        if (b) {
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R userInfo(HttpServletRequest request) {
        String idStr = tokenHelper.convertToken(request);
        if (!StringUtils.isEmpty(idStr)) {
            User user = userService.getById(Integer.parseInt(idStr));
            if (null != user) {
                HashMap<String, Object> res = new HashMap<>();
                res.put("roles", "roles");
                res.put("name", user.getUserName());
                res.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
                return R.ok().data("data", res);
            } else {
                return R.error();
            }
        } else {
            return R.error();
        }
    }
}
